package com.geek.novel.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ListView
import com.geek.novel.R
import com.geek.novel.entity.BookRead
import com.geek.novel.fragment.FragmentMyBook
import com.geek.novel.utils.LogCatUtil

/**
 * 弹出菜单列表的弹框
 */
open class MenuListDialog(context: Context, private val resourceId: Int, val list: ArrayList<MenuItem>)
    : BaseDialog(context, R.layout.dialog_base_menu_list) {

    /**菜单列表的适配器*/
    private lateinit var listViewAdapter: ListAdapter

    /**绑定事件*/
    override fun bindEvent(dialogView: View) {
        val listView = dialogView.findViewById<ListView>(R.id.lv_dialog_menu_list)
        listViewAdapter = ListAdapter(context, resourceId, list)
        listView.adapter = listViewAdapter
        listView.onItemClickListener = AdapterView.OnItemClickListener {_, view, position, _ ->
            run {
                //判断是删除还是置顶
                if(this.onItemClickListener != null){
                    //出发点击事件
                    val closeable = this.onItemClickListener?.onItemClick(this.list[position], view, position)
                    //关闭弹框
                    if(closeable != null && closeable != false){
                        this.dismiss()
                    }
                }
            }
        }
    }

    /**ListView点击事件的监听器*/
    var onItemClickListener: MenuItemClickListener? = null
    interface MenuItemClickListener{
        fun onItemClick(item: MenuItem, view: View, position: Int): Boolean
    }

    /**布局填充的监听器*/
    var inflaterViewListener: InflaterViewListener? = null
    interface InflaterViewListener{
        fun inflaterItemView(view: View, item: MenuItem)
    }

    /**设置弹框显示隐藏的动画效果*/
    override fun animationStyle(): Int = R.style.dialog_anim_style_menu_list

    open class MenuItem(open var key: String, open var name: String)

    /**更新菜单组件*/
    fun updateMenuItem(key: String, menuItem: MenuItem){
        for (item in list) {
            if(key == item.key){
                item.name = menuItem.name
            }
        }
        this.notifyDataSetChanged()
    }

    /**刷新适配器内容*/
    open fun notifyDataSetChanged(){
        listViewAdapter.notifyDataSetChanged()
    }

    /**ListView的适配器*/
    inner class ListAdapter(context: Context, private var resourceId: Int, private var list: List<MenuItem>) : ArrayAdapter<MenuItem>(context, resourceId, list) {
        @SuppressLint("ViewHolder", "SetTextI18n")
        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
            val view = LayoutInflater.from(context).inflate(resourceId, null)
            if(inflaterViewListener != null){
                inflaterViewListener!!.inflaterItemView(view, list[position])
            }
            return view
        }
    }

}